<?php

namespace App\Morefun\Quiz\Dumper;

use Illuminate\Support\Collection;
use PHPExcel;
use PHPExcel_IOFactory;

class FillBlankExcelDumper implements Dumper
{
    const FILE_EXT = 'xlsx';
    protected $users;
    protected $quizzes;

    public function __construct(array $users, Collection $quizzes)
    {
        $this->users = $users;
        $this->quizzes = $quizzes;
    }

    public function download($filename)
    {
        if (headers_sent()) {
            throw new \HttpException('[ERROR]: Headers already sent');
        }

        $headers = [
            'Content-Type'        => '	application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition' => 'attachment; filename="' . $filename . '.xlsx"',
            'Expires'             => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past
            'Last-Modified'       => date('D, d M Y H:i:s'),
            'Cache-Control'       => 'cache, must-revalidate',
            'Pragma'              => 'public'
        ];

        foreach ($headers as $header => $value) {
            header($header . ': ' . $value);
        }

        // set stream
        $this->dump();
    }

    public function dump()
    {
        $excel = $this->parse();
        $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $writer->save('php://output');
    }

    protected function parse()
    {
        $excel = new PHPExcel();
        $this->applyProperties($excel);
        $this->applyTitles($excel);

        // 设置活动记录簿
        $sheet = $excel->setActiveSheetIndex(0);

        // 缓存用户
        $users = $this->users;

        // 开始写数据的行
        $line = 2;
        foreach ($this->quizzes as $i => $quiz) {
            $sheet->mergeCells(sprintf("A%d:C%d", $line, $line))
                ->setCellValue("A".$line, $quiz['title']);

            foreach ($quiz['sheets'] as $e) {
                ++$line;

                $uid = $e->paper->uid;

                if (isset($users[$uid])) {
                    $sheet->setCellValue("A".$line, $users[$uid]['nickname']);
                    $sheet->setCellValue("B".$line, $users[$uid]['mobile']);
                } else {
                    $sheet->setCellValue("A".$line, '--');
                    $sheet->setCellValue("B".$line, '--');
                }

                $sheet->setCellValue("C".$line, implode('|', $e['fill_content']));
            }

            ++$line;
        }

        return $excel;
    }

    protected function applyProperties(PHPExcel $excel)
    {
        $excel->getProperties()
            ->setCreator("fatrbaby")
            ->setLastModifiedBy("fatrbaby")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
    }

    protected function applyTitles(PHPExcel $excel)
    {
        $excel->setActiveSheetIndex(0)
            ->setCellValue('A1', '昵称')
            ->setCellValue('B1', '电话')
            ->setCellValue('C1', '内容');
    }
}
